package cn.smile.config.spring.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: 毛苏宇
 * @Description: You can do it!
 * @Date: Create in 13:05 2019/4/25
 */
@Configuration
public class RedisConfig {

    /**
     * redis连接池配置
     *
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(200);
        jedisPoolConfig.setMaxIdle(50);
        jedisPoolConfig.setMaxWaitMillis(3000);
        jedisPoolConfig.setTestOnBorrow(true);
        return jedisPoolConfig;
    }



    /**
     * Redis链接工厂,哨兵模式
     *
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfiguration(),jedisPoolConfig());
        jedisConnectionFactory.setPassword("MaoSuyu123123");
        return jedisConnectionFactory;
    }





    /**
     * redisTemplate
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate redisTemplate=new RedisTemplate();
        StringRedisSerializer serializer=new StringRedisSerializer();
        //key序列化方式
        redisTemplate.setKeySerializer(serializer);
        //value序列化方式
        redisTemplate.setValueSerializer(serializer);
        //加入连接工厂
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        //启用事务支持，必须配合@Transactional一起使用，否则连接不会close
        redisTemplate.setEnableTransactionSupport(true);
        return redisTemplate;
    }


    /**
     * 哨兵模式配置
     * @return
     */
    @Bean
    public RedisSentinelConfiguration sentinelConfiguration(){
        //哨兵配置
        RedisSentinelConfiguration configuration=new RedisSentinelConfiguration();
        //哨兵的名字
        configuration.setMaster("Master");
        //多个哨兵配置，这里只有一个哨兵
        Set<RedisNode> redisNodes = new HashSet<RedisNode>();
        redisNodes.add(new RedisNode("47.105.164.51",26379));
        redisNodes.add(new RedisNode("47.105.164.51",36379));
        //添加
        configuration.setSentinels(redisNodes);
        return configuration;
    }



}
